import { useRef, useEffect } from 'preact/hooks'

export function useInterval(callback: () => void, delay: number | null) {
  const savedCallback = useRef(() => {})

  useEffect(() => {
    savedCallback.current = callback
  })

  useEffect(() => {
    if (delay === null) {
      return
    }
    const handler = () => savedCallback.current()
    const id = setInterval(handler, delay)
    return () => clearInterval(id)
  }, [delay])
}
